import React, { Component } from 'react';
// import {SingleElectricityLine} from '@/components/Chart/ElectricityLine.ts';
import { queryDeviceWisdomElectricityCurrent } from '../service';
import { getQueryString } from '@/utils/util';
import { SingleFigure } from '@/components/Chart/Figure';

function flatten(arr, result = []) {
  for (let item of arr) {
    if (Array.isArray(item))
      flatten(item, result)
    else
      result.push(item)
  }
  return result
}

const groupBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
    acc[val] = (acc[val] || []).concat(arr[i]);
    return acc;
  }, {});


export default class WaveformFigureLeft extends Component {

  state = {
    electricityLine: null,
    id: getQueryString('id'),
    residueCurrentValue: [],
    xAxisData: []
  };

  componentDidMount() {
    queryDeviceWisdomElectricityCurrent({ deviceId: this.state.id }).then(data => {
      if (Array.isArray(data)) {
        let dataX = [];
        const color = ['#f98b55', '#ffb53e', '#2dcef0', '#49a1ff']
        const ans = groupBy(
          flatten(
            data.map(it =>
              Object.keys(it.valueMap)
                .filter(v => v.indexOf("leakage") == 0)
                .map(u => {
                  dataX.push(it.createTime)
                  return ({ key: u, value: it.valueMap[u] })
                })
            )
          ), 'key')

        const v = Object.values(ans).map((it: Array<{ value: string }>, index) => ({
          name: `剩余电流${index + 1}/°C`,
          type: 'line',
          color: color[index],
          data: it.map(u => u.value)
        }))

        SingleFigure({
          ref: this.state.electricityLine,
          color,
          dataX: [...new Set(dataX)],
          data: v
        })
      }
    });
  }

  render() {
    return (
      <div>
        <div ref={(value) => this.state.electricityLine = value} style={{ 'height': '400px' }}></div>
      </div>
    )
  }
}
